﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PMS.Core.Infrastructure;
using System.Collections.Generic;
using System.Linq;

namespace PMS.Web.Framework.StartupCfgs.StartupSetups
{
    //Custom class to create custom response 
    //For FluentValidation when modelState validation.
    internal class ValidateError
    {
        public string ErrorField { get; set; }
        public string ErrorDescription { get; set; }
    }
    /// <summary>
    /// Represents object for the configuring exceptions and errors handling on application startup
    /// </summary>
    public class ErrorHandlerStartup : IPMSStartup
    {
        /// <summary>
        /// Add and configure any of the middleware
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            // override modelstate
            services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState
                        .Where(modelError => modelError.Value.Errors.Count > 0)
                        .Select(modelError => new ValidateError
                        {
                            ErrorField = modelError.Key,
                            ErrorDescription = modelError.Value.Errors.FirstOrDefault().ErrorMessage
                        }).ToList();

                    return new BadRequestObjectResult(new { 
                        ErrorCode = "FluentValidationError",
                        Errors = errors
                    });
                };
            });
        }

        /// <summary>
        /// Configure the using of added middleware
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application)
        {
            //exception handling
            application.UsePMSExceptionHandler();

            //handle 400 errors (bad request)
            application.UseBadRequestResult();

            //handle 404 errors (not found)
            application.UsePageNotFound();
        }

        /// <summary>
        /// Gets order of this startup configuration implementation
        /// </summary>
        public int Order => StartupOrderConfig.ErrorHandlerOrder; //error handlers should be loaded first
    }

}
